#include <CODEPORTS/codeports.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void
CP_Init(void)
{
	INPUT_Init();
	AUDIO_Init();
	VIDEO_Init();

	printf("CodePorts\n");
	srand(time(NULL));

	SPK_Init();
	MIC_Init();
	SCR_Init();
	KEY_Init();
	FMT_Init();
	PL_Init();
}

void
CP_Final(void)
{
	PL_Final();
	KEY_Final();
	FMT_Final();
	SCR_Final();
	MIC_Final();
	SPK_Final();

	VIDEO_Final();
	AUDIO_Final();
	INPUT_Final();
}

#ifdef CP_MAIN

int
main(int argc, char **argv)
{
	#define splits (1 << 2)
	DEMO demos[splits * splits];
	BOX boxes[splits * splits];
	int w, h, i, j;

	CP_Init();
	char buffer[128];
	for (i = 0; i < 1024 * 2.5; ++i)
	{
		MIC_ReadBuffer(buffer, 128);
		SPK_WriteBuffer(buffer, 128);
	}
	SCR_GetSize(&w, &h);

	for(j = 0; j < splits; j++)
	{
		for(i = 0; i < splits; i++)
		{
			BOX_Allocate(&boxes[j * splits + i], w / splits, h / splits);
			plugins[j * splits + i].DEMO_Init(&demos[j * splits + i], &boxes[j * splits + i]);
		}
	}

	while(!KEY_Update())
	{
		//SCR_Clear();

		for(j = 0; j < splits; j++)
		{
			for(i = 0; i < splits; i++)
			{
				BOX_Clear(demos[j * splits + i].box);
				plugins[j * splits + i].DEMO_Frame(&demos[j * splits + i]);
				SWP_SetBox(w / splits * i, h / splits * j, demos[j * splits + i].box);
			}
		}

		SWP_Screen();
	}

	for(j = 0; j < splits; j++)
	{
		for(i = 0; i < splits; i++)
		{
			plugins[j * splits + i].DEMO_Final(&demos[j * splits + i]);
			BOX_Free(demos[j * splits + i].box);
		}
	}

	//SCR_Clear();
	CP_Final();

	return EXIT_SUCCESS;
}

#endif
